import { defineStore } from 'pinia'
import { ref } from 'vue'
// 移除顶层 invoke 直接导入，避免浏览器预览环境报错
// import { invoke } from '@tauri-apps/api/core'
import { useWorkspaceStore } from './workspace'

export type AiTimelineKind = 'create' | 'modify' | 'delete' | 'move'

export interface AiTimelineChangeLine {
  line: number
  before: string
  after: string
}

// 操作特定的元数据
export interface AiTimelineOperationMeta {
  // 移动操作的源路径
  sourcePath?: string
  // 移动操作的目标路径  
  targetPath?: string
  // 操作是否为目录操作
  isDirectory?: boolean
  // 文件大小
  fileSize?: number
  // 操作前的文件状态
  beforeExists?: boolean
  // 操作后的文件状态
  afterExists?: boolean
}

export interface AiTimelineEntry {
  id: string
  ts: number
  kind: AiTimelineKind
  path: string // absolute path normalized to workspace separator
  tool?: string // e.g. workspace.applyEdits
  replacements?: number
  changes?: AiTimelineChangeLine[]
  note?: string
  // 内容相关字段
  beforeContent?: string // 修改前的完整文件内容
  afterContent?: string // 修改后的完整文件内容
  // 操作元数据
  operationMeta?: AiTimelineOperationMeta
  // 向后兼容的字段（逐步废弃）
  fileSize?: number // 文件大小
  isDirectory?: boolean // 是否为目录操作
}

function makeId() {
  return `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
}

export const useAiTimelineStore = defineStore('aiTimeline', () => {
  const entries = ref<AiTimelineEntry[]>([])
  const loadedKey = ref<string | null>(null)

  // 获取当前工作区
  function getWorkspace() {
    const ws = useWorkspaceStore()
    return ws.workspaceRoot || ''
  }

  // 获取当前会话ID（从 Tauri app setting 读取）
  async function getSessionId(): Promise<string> {
    try {
      const { invoke } = await import('@tauri-apps/api/core')
      const v = await invoke<string>('get_app_setting', { key: 'chat.session.active' })
      if (typeof v === 'string' && v) return v
    } catch {}
    return 'default'
  }

  async function ensureLoaded() {
    const workspace = getWorkspace()
    const sessionId = await getSessionId()
    const key = `${workspace || ''}::${sessionId}`
    if (loadedKey.value === key) return

    // Tauri 模式：从数据库读取（需要已选择工作区）
    if (!workspace) { entries.value = []; loadedKey.value = key; return }
    try {
      const { invoke } = await import('@tauri-apps/api/core')
      const list = await invoke<AiTimelineEntry[]>('ai_timeline_list', { workspace, sessionId })
      entries.value = Array.isArray(list) ? list : []
    } catch (e) {
      console.warn('Load AI timeline from DB failed:', e)
      entries.value = []
    }
    loadedKey.value = key
  }

  async function addEntry(partial: Omit<AiTimelineEntry, 'id' | 'ts'> & { ts?: number }) {
    await ensureLoaded()
    const entry: AiTimelineEntry = {
      id: makeId(),
      ts: partial.ts ?? Date.now(),
      kind: partial.kind,
      path: partial.path,
      tool: partial.tool,
      replacements: partial.replacements,
      changes: partial.changes,
      note: partial.note,
      beforeContent: partial.beforeContent,
      afterContent: partial.afterContent,
      operationMeta: partial.operationMeta,
      fileSize: partial.fileSize,
      isDirectory: partial.isDirectory,
    }
    entries.value.push(entry)

    const workspace = getWorkspace()
    const sessionId = await getSessionId()

    // 将新增条目写入持久化层
    if (workspace) {
      try {
        const { invoke } = await import('@tauri-apps/api/core')
        await invoke('ai_timeline_add', { workspace, sessionId, entry })
      } catch (e) {
        console.warn('Persist AI timeline entry failed:', e)
      }
    }
    return entry
  }

  async function loadEntries() {
    await ensureLoaded()
    return entries.value.slice().sort((a, b) => b.ts - a.ts)
  }

  // 新增：根据文件路径获取相关的时间线条目
  async function getEntriesForFile(filePath: string) {
    await ensureLoaded()
    const normalizedPath = filePath.replace(/[\\\/]/g, '/')
    return entries.value
      .filter((entry) => {
        const entryPath = entry.path.replace(/[\\\/]/g, '/')
        return entryPath === normalizedPath
      })
      .sort((a, b) => b.ts - a.ts)
  }

  // 验证文件/目录是否存在
  async function checkPathExists(path: string): Promise<boolean> {
    const { invoke } = await import('@tauri-apps/api/core')
    try {
      await invoke('fs_stat', { path })
      return true
    } catch {
      return false
    }
  }

  // 验证回退操作的可行性
  async function validateRollbackOperation(entry: AiTimelineEntry): Promise<{ canRollback: boolean; reason?: string }> {
    const pathExists = await checkPathExists(entry.path)
    
    switch (entry.kind) {
      case 'delete':
        // 删除操作回退：需要beforeContent，目标路径不应存在
        if (!entry.beforeContent) {
          return { canRollback: false, reason: 'No before content available for delete rollback' }
        }
        if (pathExists) {
          return { canRollback: false, reason: 'Target path already exists, cannot restore deleted file' }
        }
        return { canRollback: true }
        
      case 'create':
        // 创建操作回退：目标路径应该存在
        if (!pathExists) {
          return { canRollback: false, reason: 'Created file/directory no longer exists' }
        }
        return { canRollback: true }
        
      case 'modify':
        // 修改操作回退：需要beforeContent，目标路径应该存在
        if (!entry.beforeContent) {
          return { canRollback: false, reason: 'No before content available for modify rollback' }
        }
        if (!pathExists) {
          return { canRollback: false, reason: 'Modified file no longer exists' }
        }
        return { canRollback: true }
        
      case 'move':
        // 移动操作回退：需要operationMeta，目标路径应该存在，源路径不应存在
        if (!entry.operationMeta?.sourcePath) {
          return { canRollback: false, reason: 'No source path information for move rollback' }
        }
        if (!pathExists) {
          return { canRollback: false, reason: 'Moved file/directory no longer exists at target location' }
        }
        const sourceExists = await checkPathExists(entry.operationMeta.sourcePath)
        if (sourceExists) {
          return { canRollback: false, reason: 'Source path is occupied, cannot move back' }
        }
        return { canRollback: true }
        
      default:
        return { canRollback: false, reason: `Unknown operation kind: ${entry.kind}` }
    }
  }

  // 回退文件到指定的时间线条目状态
  async function rollbackToEntry(entryId: string, opts?: { log?: boolean; force?: boolean }) {
    await ensureLoaded()
    const entry = entries.value.find((e) => e.id === entryId)
    if (!entry) {
      throw new Error(`Timeline entry not found: ${entryId}`)
    }

    // 验证回退操作的可行性（除非强制执行）
    if (!opts?.force) {
      const validation = await validateRollbackOperation(entry)
      if (!validation.canRollback) {
        throw new Error(`Cannot rollback: ${validation.reason}`)
      }
    }

    const { invoke } = await import('@tauri-apps/api/core')

    try {
      switch (entry.kind) {
        case 'delete':
          // 删除操作的回退：重新创建文件
          if (entry.beforeContent) {
            await invoke('fs_write_text', {
              path: entry.path,
              content: entry.beforeContent,
              createDirs: true,
            })
          }
          break
          
        case 'create':
          // 创建操作的回退：删除文件
          await invoke('fs_delete', { path: entry.path, recursive: true })
          break
          
        case 'modify':
          // 修改操作的回退：恢复到修改前的内容
          if (entry.beforeContent) {
            await invoke('fs_write_text', {
              path: entry.path,
              content: entry.beforeContent,
              createDirs: true,
            })
          }
          break
          
        case 'move':
          // 移动操作的回退：将文件从目标位置移回源位置
          if (entry.operationMeta?.sourcePath) {
            await invoke('fs_rename', {
              from: entry.path, // 当前位置（目标位置）
              to: entry.operationMeta.sourcePath // 原始位置
            })
          }
          break
          
        default:
          throw new Error(`Unsupported rollback operation: ${entry.kind}`)
      }

      // 可选：记录回退操作到时间线（默认记录，允许关闭）
      if (opts?.log !== false) {
        const rollbackKind = entry.kind === 'delete' ? 'create' : 
                           entry.kind === 'create' ? 'delete' : 
                           entry.kind === 'move' ? 'move' : 'modify'
        
        const rollbackEntry: Partial<AiTimelineEntry> = {
          kind: rollbackKind,
          path: entry.kind === 'move' ? entry.operationMeta?.sourcePath || entry.path : entry.path,
          tool: 'ai.rollback',
          note: `Rollback to ${new Date(entry.ts).toLocaleString()}`,
          beforeContent: entry.afterContent,
          afterContent: entry.beforeContent,
        }
        
        // 为移动操作的回退添加特殊的operationMeta
        if (entry.kind === 'move' && entry.operationMeta) {
          rollbackEntry.operationMeta = {
            sourcePath: entry.operationMeta.targetPath,
            targetPath: entry.operationMeta.sourcePath,
            isDirectory: entry.operationMeta.isDirectory,
            beforeExists: entry.operationMeta.afterExists,
            afterExists: entry.operationMeta.beforeExists
          }
        }
        
        await addEntry(rollbackEntry as AiTimelineEntry)
      }

      return true
    } catch (error: any) {
      console.error('Rollback failed:', error)
      throw error
    }
  }

  // 新增：获取文件的最新 AI 修改记录
  async function getLatestEntryForFile(filePath: string) {
    const entries = await getEntriesForFile(filePath)
    return entries.length > 0 ? entries[0] : null
  }

  // 新增：全部回退 - 按时间倒序回退所有AI操作
  async function rollbackAll(opts?: { log?: boolean, clear?: boolean, force?: boolean }) {
    await ensureLoaded()
    const sortedEntries = entries.value.slice().sort((a, b) => b.ts - a.ts)

    if (sortedEntries.length === 0) {
      return { success: true, count: 0 }
    }

    let successCount = 0
    const errors: Array<{ entryId: string; error: string }> = []

    // 如果不是强制模式，先验证所有操作的可行性
    if (!opts?.force) {
      for (const entry of sortedEntries) {
        const validation = await validateRollbackOperation(entry)
        if (!validation.canRollback) {
          errors.push({ entryId: entry.id, error: validation.reason || 'Validation failed' })
        }
      }
      
      // 如果有验证失败的操作，提前返回
      if (errors.length > 0) {
        return {
          success: false,
          count: 0,
          errors
        }
      }
    }

    for (const entry of sortedEntries) {
      try {
        await rollbackToEntry(entry.id, { log: opts?.log, force: opts?.force })
        successCount++
      } catch (error: any) {
        console.error(`Failed to rollback entry ${entry.id}:`, error)
        errors.push({ entryId: entry.id, error: error.message })
      }
    }

    // 可选：回退后清空时间线
    if (opts?.clear) {
      try { await clearTimeline() } catch {}
    }

    return {
      success: errors.length === 0,
      count: successCount,
      errors: errors.length > 0 ? errors : undefined,
    }
  }

  // 新增：回退从指定时间点开始的所有变更
  async function rollbackFromTimestamp(timestamp: number, opts?: { log?: boolean, clear?: boolean, force?: boolean }) {
    await ensureLoaded()
    const entriesToRollback = entries.value
      .filter(entry => entry.ts >= timestamp)
      .sort((a, b) => b.ts - a.ts) // 按时间倒序回退

    if (entriesToRollback.length === 0) {
      return { success: true, count: 0 }
    }

    let successCount = 0
    const errors: Array<{ entryId: string; error: string }> = []

    // 如果不是强制模式，先验证所有操作的可行性
    if (!opts?.force) {
      for (const entry of entriesToRollback) {
        const validation = await validateRollbackOperation(entry)
        if (!validation.canRollback) {
          errors.push({ entryId: entry.id, error: validation.reason || 'Validation failed' })
        }
      }
      
      // 如果有验证失败的操作，提前返回
      if (errors.length > 0) {
        return {
          success: false,
          count: 0,
          errors
        }
      }
    }

    for (const entry of entriesToRollback) {
      try {
        await rollbackToEntry(entry.id, { log: opts?.log, force: opts?.force })
        successCount++
      } catch (error: any) {
        console.error(`Failed to rollback entry ${entry.id}:`, error)
        errors.push({ entryId: entry.id, error: error.message })
      }
    }

    // 可选：回退后清空相关时间线条目
    if (opts?.clear) {
      // 使用splice方法保持数组引用不变，确保Vue响应式系统能正确监听到变化
      const indicesToRemove: number[] = []
      entries.value.forEach((entry, index) => {
        if (entry.ts >= timestamp) {
          indicesToRemove.push(index)
        }
      })
      
      // 从后往前删除，避免索引偏移问题
      for (let i = indicesToRemove.length - 1; i >= 0; i--) {
        entries.value.splice(indicesToRemove[i], 1)
      }
      
      console.log(`[AI时间线] 清空了 ${indicesToRemove.length} 个条目，剩余 ${entries.value.length} 个条目`)
      
      const workspace = getWorkspace()
      const sessionId = await getSessionId()
      
      if (workspace) {
        try {
          const { invoke } = await import('@tauri-apps/api/core')
          await invoke('ai_timeline_clear_from', { workspace, sessionId, fromTimestamp: timestamp })
        } catch (e) {
          console.warn('Clear AI timeline from timestamp in DB failed:', e)
        }
      }
    }

    return {
      success: errors.length === 0,
      count: successCount,
      errors: errors.length > 0 ? errors : undefined,
    }
  }

  // 新增：清空时间线（按工作区+会话范围）
  async function clearTimeline() {
    // 使用splice方法清空数组，保持引用不变，确保Vue响应式系统能正确监听到变化
    const removedCount = entries.value.length
    entries.value.splice(0, entries.value.length)
    console.log(`[AI时间线] 清空了所有 ${removedCount} 个条目`)

    const workspace = getWorkspace()
    const sessionId = await getSessionId()

    if (workspace) {
      try {
        const { invoke } = await import('@tauri-apps/api/core')
        await invoke('ai_timeline_clear', { workspace, sessionId })
      } catch (e) {
        console.warn('Clear AI timeline in DB failed:', e)
      }
    }

    return { success: true, count: 0 }
  }

  return {
    entries,
    addEntry,
    loadEntries,
    getEntriesForFile,
    rollbackToEntry,
    getLatestEntryForFile,
    rollbackAll,
    rollbackFromTimestamp,
    clearTimeline,
  }
})